package mobilesmil.activity;

import java.util.regex.Pattern;

import mobilesmil.services.MessageSender;
import mobilesmil.utils.FormValidationUtils;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
 * This activity allows users to send the file to another user by manually typing the number in or selecting from the contacts.
 */
public class SendActivity extends Activity {

	private Button mBtnSend;
	private String mFileName;
	private EditText mEditPhoneNumber;
	
	private static final byte DIALOG_FORM_INVALID_ID = 0;
	private static String mDialogInvalidFormTitle = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.send_form);
		mBtnSend = (Button)findViewById(R.id.btnSend);
		mEditPhoneNumber = (EditText)findViewById(R.id.editPhoneNumber);
		
		Bundle extras = this.getIntent().getExtras();
		if(extras != null)
		{
			if(this.getIntent().hasExtra(this.getString(R.string.fileName)))
				mFileName = extras.getString(this.getString(R.string.fileName));
			else
				mBtnSend.setEnabled(false);
		}
		else
			mBtnSend.setEnabled(false);
		
		mBtnSend.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if(fieldsAreValid())
					sendFile();
				else
					showDialog(DIALOG_FORM_INVALID_ID);
			}
		});
	}
	
	/**
	 * This will get a the phone current users phone number followed by launching a sender thread.
	 * This is to allow the send to run in the background and on the UI thread since it is intensive.
	 */
	private void sendFile() {
		String toPhoneNumber = mEditPhoneNumber.getText().toString();
		String fromPhoneNumber = null;
	//	TelephonyManager telephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
	//	fromPhoneNumber = telephonyMgr.getLine1Number();
		fromPhoneNumber = this.getString(R.string.emulator_phone_number);
		
		if(fromPhoneNumber != null) {
			Runnable sender = new MessageSender(toPhoneNumber, fromPhoneNumber, mFileName, this);
			Thread senderThread = new Thread(sender);
			senderThread.start();
			Toast.makeText(this, "Sending Message", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * This will calls the intent for accessing the contacts activity built into the phone
	 * @param v
	 */
	public void pickContact(View v){
		Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
		startActivityForResult(i, 1);
	}
	
	/**
	 * Strips the contact ID out of the URI returned from contacts and gets the mobile number.
	 * @param uri
	 */
	private void getContact(Uri uri){
		ContentResolver cr = getContentResolver();
		String id = uri.toString().substring(uri.toString().length() - 1);
		Cursor phoneCursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", 
				new String[] {id}, null);
		while(phoneCursor.moveToNext())
		{
			if(phoneCursor.getInt(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE)) == 2)
			{
				mEditPhoneNumber.setText(phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
				break;
			}
				
		}
    }
	
	@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(data != null)
			getContact(data.getData());
	}

	/**
	 * Validates the phone number.
	 * @return
	 */
	private boolean fieldsAreValid() {
		String value = mEditPhoneNumber.getText().toString();
		String integerRegex = FormValidationUtils.INTEGER_REGEX;
		
		if(value.length() == 0) {
			mDialogInvalidFormTitle = "Please enter a phone number.";
			return false;
		}
		
		if(Pattern.matches(integerRegex, value))
			return true;
		else {
			mDialogInvalidFormTitle = "Please enter a valid phone number.";
			return false;
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		super.onCreateDialog(id);
		Dialog dialog = null;
		switch(id)
		{
			case DIALOG_FORM_INVALID_ID:
		        dialog = FormValidationUtils.createInvalidFormDialog(this);
		        dialog.setTitle(mDialogInvalidFormTitle);
				break;
		}
		return dialog;
	}
	
	/**
	 * Shows a toast.
	 * @param msg
	 */
	public void showMessage(final String msg){
		final Context con = this;
		Runnable msgRun = new Runnable(){
			@Override public void run(){Toast.makeText(con, msg, Toast.LENGTH_SHORT).show();}
		};
		
		runOnUiThread(msgRun);
	}
}
